<template>
  <el-card class="box-card" style="width: 100%;">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>CPI分析</el-breadcrumb-item>
      <el-breadcrumb-item>按类别分析</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row style="margin: 10px auto 5px auto;">
      <el-col :span="10">
        <el-button class="but icon" @click="show(3)">&#xe65f;</el-button>
        <el-button class="icon but" @click="show(0)">&#xeb97;</el-button>
        <el-button class="but icon" @click="show(1)">&#xeb96;</el-button>
        <el-button class="but icon" @click="show(2)">&#xe621;</el-button>
        <!-- 收藏按钮 -->
        <el-button v-show="!collectFlag" @click="collectDialogFlag = true" class="but el-icon-star-off"
          style="font-size: 30px;"></el-button>
        <!-- 取消收藏 -->
        <el-button v-show="collectFlag" @click="unCollect()" class="but el-icon-star-off"
          style="font-size: 30px;color: deepskyblue;"></el-button>
        <!-- 收藏列表 -->
        <el-button @click="collectListFlag=true" class="but el-icon-collection-tag" style="font-size: 30px;">
        </el-button>
      </el-col>
      <el-col :span="6" :offset="2">类别：
        <el-select v-model="type" placeholder="请选择" @change="listPage()">
          <el-option v-for="(item,index) in options1" :key="index" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">时间：
        <el-select v-model="time" placeholder="请选择" @change="listPage()">
          <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div id="test" style="width: 500px;height: 500px;display: none; margin: auto auto;"></div>
    <el-table ref='table' :data="tableData" style="width: 100%;" highlight-current-row @row-click="handleSelectionChange">
      <el-table-column sortable fixed prop="province" width="180px" label="省份">
        <template slot-scope="scope">
          <el-radio v-if="template" v-model="radioSelected" :label="scope.row.province"
            @change.native="handleSelectionChange(scope.row)">
          </el-radio>
          <span v-if="!template">{{scope.row.province}}</span>
        </template>
      </el-table-column>
      <el-table-column sortable v-for="(item,index) in timelist" :prop="item" :key="index" :label="item" width="180px"
        :value="item">
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pager.page"
      :page-sizes="[5,10, 15, 20]" :page-size="pager.size" layout="total, sizes, prev, pager, next, jumper"
      :total="pager.total">
    </el-pagination>

    <!-- 收藏夹弹窗-->
    <el-dialog title="收藏表格" :visible.sync="collectDialogFlag" width="40%">
      <el-form :model="form">
        <el-form-item label="名  称" label-width="50px">
          <el-input v-model="query.collectname" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="collectDialogFlag = false">取 消</el-button>
        <el-button type="primary" @click="collecting()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 收藏列表弹窗 -->
    <el-drawer title="收藏列表" :wrapperClosable="false" :visible.sync="collectListFlag" direction="rtl">
      <el-main>
        <el-radio-group v-for="item in listForm" :key="item.id" v-model="collectionId" style="display: block;">
          <el-radio :label="item.id" style="padding-bottom: 15px;">
            <el-tag>{{item.collectname}}</el-tag>
            <span style="margin-left: 15px;">{{item.type}}---最近{{item.time}}个月</span>
          </el-radio>
        </el-radio-group>
      </el-main>

      <el-footer>
        <el-button @click="collectListFlag = false">取 消</el-button>
        <el-button type="primary" @click="updatePage()">确 定</el-button>
      </el-footer>
    </el-drawer>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        collectionId: 0,
        listForm: [],
        collectListFlag: false,
        collectDialogFlag: false,
        collectFlag: false,
        template: false,
        radioSelected: null,
        tableData: [],
        pager: {
          page: 1,
          size: 5,
          total: 32
        },
        time: 6,
        timelist: [],
        query: {
          province: '',
          time: 6,
          type: "居民消费价格指数",
          collectname: ""
        },
        type: "居民消费价格指数",
        options1: [],
        options2: [{
            value: 6,
            label: '最近6个月'
          },
          {
            value: 12,
            label: '最近12个月'
          },
          {
            value: 24,
            label: '最近24个月'
          },
        ],
        flag: 3,
        data: [],
        min: 97,
        max: 108,
        bing: [],
        dialogFormVisible: false,
        form: {
          collections: '默认收藏夹',
          name: 'cpi'
        }
      };
    },
    methods: {
      // 渲染收藏列表
      listCollection() {
        this.listForm = []
        this.$http.get('apis/collection/selectProvince').then(res => {
          this.listForm = res.data;
        })
      },
      // 跳转对应的收藏表格
      updatePage() {
        // 连接后端获取收藏的地区和时间段
        this.$http.get('apis/collection/getByid', {
          params: {
            id: this.collectionId
          }
        }).then(res => {
          this.time = res.data[0].time
          this.type = res.data[0].type
          this.listPage()
          this.collectListFlag = false; //收藏列表（抽屉）不显示
          this.$message({
            message: '跳转成功！！',
            type: 'success'
          });
        })
      },
      // 添加收藏记录
      collecting() {
        this.query.time = this.time;
        this.query.type = this.type;
        this.$http.post('apis/collection/collecting', this.query)
          .then(res => {
            this.collectFlag = true
            this.collectDialogFlag = false;
            this.$message({
              message: '收藏成功！！',
              type: 'success'
            });
            this.listCollection()
          })
      },
      //取消收藏
      unCollect() {
        this.query.time = this.time;
        this.query.type = this.type;
        this.$http.post('apis/collection/delete', this.query)
          .then(res => {
            this.collectFlag = false
            this.$message({
              message: '取消收藏成功！！',
              type: 'success'
            });
            this.listCollection()
          })
      },
      handleSelectionChange(val) {
        this.radioSelected = val.province
        for (let i = 0; i < this.timelist.length; i++) {
          this.data[i] = val[this.timelist[i]];
        }
        this.max = Math.ceil(Math.max.apply(null, this.data)) + 1;
        this.min = Math.floor(Math.min.apply(null, this.data)) - 1;
        this.show(this.flag)
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pager.size = val;
        this.listPage();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pager.page = val;
        this.listPage();
      },
      listPage() {
        this.$http.get('apis/cpi/byprovince', {
          params: {
            page: this.pager.page,
            size: this.pager.size,
            time: this.time,
            type: this.type
          }
        }).then(res => {
          // 获取属性值数组
          let arr = Object.getOwnPropertyNames(res.data[0])
          arr = arr.filter((item) => {
            return item != 'province';
          });
          // 初始化
          this.timelist = [];
          this.data = [];
          this.timelist = arr.sort((a, b) => a < b ? 1 : a > b ? -1 : 0)
          this.tableData = res.data;
          for (let i = 0; i < this.timelist.length; i++) {
            this.data[i] = this.tableData[0][this.timelist[i]];
          }

          this.radioSelected = this.tableData[0]["province"]

          this.max = Math.ceil(Math.max.apply(null, this.data)) + 1;
          this.min = Math.floor(Math.min.apply(null, this.data)) - 1;

          this.bing = [];
          for (let i = 0; i < this.timelist.length; i++) {
            this.bing.push({
              name: this.timelist[i],
              value: this.data[i]
            });
          }
          this.show(this.flag)
          this.isCollect();
          //table显示错位问题
          this.$nextTick(() => {
                // table是表格的ref属性值
                if (this.$refs.table && this.$refs.table.doLayout) {
                  this.$refs.table.doLayout();
                }
          })
        }).catch(error => {
          this.$message.error('网络异常')
        })
      },
      isCollect() {
        this.query.time = this.time;
        this.query.type = this.type;
        // 当前选项是否被收藏
        this.$http.get('apis/collection/isProvince', {
          params: {
            type: this.query.type,
            time: this.query.time
          }
        }).then(res => {
          this.collectFlag = res.data ? true : false;
        })
      },
      getalltype() {
        this.$http.get('apis/cpi/alltype')
          .then(res => {
            this.options1 = res.data
          })
      },
      show(x) {
        let test = document.getElementById("test");
        this.flag = x;
        if (x == 3) {
          test.style.display = "none";
          this.template = false
          return;
        }
        test.style.display = "block";
        this.template = true
        let myEcharts = this.$echarts.init(test);
        myEcharts.clear();
        let option;
        if (x == 1) {
          option = {
            tooltip: {
              trigger: 'axis',
              position: function(point, params, dom, rect, size) {
                //  size为当前窗口大小
                if ((size.viewSize[0] / 2) >= point[0]) {
                  //其中point为当前鼠标的位置
                  return [point[0] + 50, '10%'];
                } else {
                  //其中point为当前鼠标的位置
                  return [point[0] - 200, '10%'];
                }
              }
            },
            xAxis: {
              type: 'category',
              data: this.timelist
            },
            yAxis: {
              type: 'value',
              interval: 1,
              min: this.min,
              max: this.max
            },
            series: [{
              data: this.data,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)'
              },
            }]
          };
        } else if (x === 0) {
          option = {
            tooltip: {
              trigger: 'axis',
              position: function(point, params, dom, rect, size) {
                //  size为当前窗口大小
                if ((size.viewSize[0] / 2) >= point[0]) {
                  //其中point为当前鼠标的位置
                  return [point[0] + 50, '10%'];
                } else {
                  //其中point为当前鼠标的位置
                  return [point[0] - 200, '10%'];
                }
              }
            },
            xAxis: {
              type: 'category',
              data: this.timelist
            },
            yAxis: {
              type: 'value',
              interval: 1,
              min: this.min,
              max: this.max
            },
            series: [{
              data: this.data,
              type: 'line'
            }]
          };
        } else if (x === 2) {
          option = {
            tooltip: {
              trigger: 'item'
            },
            legend: {
              top: '5%',
              left: 'center'
            },
            series: [{
              name: 'CPI',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '40',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: this.bing
            }]
          };
        }
        myEcharts.setOption(option);
      },
      collection() {
        this.$message({
          message: '收藏成功！！',
          type: 'success'
        });
        this.collect = true;
        this.dialogFormVisible = false;
      }
    },
    created() {
      this.listCollection();
      this.listPage();
      this.getalltype();
    },
    updated() {
        // table是表格的ref属性值
        if (this.$refs.table && this.$refs.table.doLayout) {
          this.$refs.table.doLayout();
        }
    }
  }
</script>

<style scoped>
  .but {
    border: 0px;
    padding: 10px;
  }
</style>
